<template>
  <view class="container">
    <hello-title></hello-title>
    <view class="circle-card">
      <view class="content">
        <view class="target">
          <text class="text">{{ latestSleepData }}</text>
          <text class="unit">小时</text>
        </view>
        <circle-progress-bar :width="210" :height="210"></circle-progress-bar>
      </view>
    </view>
    <!--    输入睡眠和醒来时间-->
    <view class="sleep-edit-card-area" @tap="showCreateActionSheet">
      <view class="sleep-edit-card sleep-edit-card--purple">
        <view class="sleep-edit-card__header">
          <view class="icon-sunrise"></view>
          <view class="icon-pen"></view>
        </view>
        <view class="sleep-edit-card__body">
          <text class="sleep-edit-card__title">{{startSleepTime}}</text>
          <text class="sleep-edit-card__subtitle">入睡</text>
        </view>
      </view>
      <view class="divider" style="width: 15px"></view>
      <view class="sleep-edit-card sleep-edit-card--orange" @tap="showWakeUpCreateActionSheetOpen">
        <view class="sleep-edit-card__header">
          <view class="icon-moon"></view>
          <view class="icon-pen"></view>
        </view>
        <view class="sleep-edit-card__body">
          <text class="sleep-edit-card__title">{{wakeUpTime}}</text>
          <text class="sleep-edit-card__subtitle sleep-edit-card__subtitle--orange">醒来</text>
        </view>
      </view>
    </view>
    <!-- 图表卡片   -->
    <view class="line-card">
      <view class="line-card__tabs">
        <view class="line-card__tab" @tap="showWeekChart"
              :class="{'line-card__tab--active':sleepChartDateType===1}">
          每周
        </view>
        <view class="line-card__tab" @tap="showMonthChart"
              :class="{'line-card__tab--active':sleepChartDateType===2}">
          每月
        </view>
      </view>
      <!--  注意:因为 canvas 不能重绘的原因,无法使用 v-if    -->
      <view class="line-card__content" :class="{'line-card__content--hidden':sleepChartDateType!==1}">
        <line-chart :config="weekChartData" v-if="weekChartData" id="weekly-chart"></line-chart>
      </view>
      <view class="line-card__content" :class="{'line-card__content--hidden':sleepChartDateType!==2}">
        <line-chart :config="monthChartData" v-if="monthChartData" id="monthly-chart"></line-chart>
      </view>

    </view>
    <!--    底部操作栏-->
    <AtModal :isOpened="isCreateActionSheetOpen" :onClose="handleSleepTimeClose">
      <AtModalContent>
        <view>
          <picker
            mode='date'
            :value="startSleepDate"
            @change="sleepDateChange"
          >
            <view class='input-row'>
              <view class='input-row__label'>入睡日期</view>
              <view class='input-row__content'>{{startSleepDate}}</view>
            </view>
          </picker>
        </view>
        <view>
          <picker
            mode='time'
            :value="startSleepTime"
            @change="sleepTimeChange"
          >
            <view class='input-row'>
              <view class='input-row__label'>入睡时间</view>
              <view class='input-row__content'>{{startSleepTime}}</view>
            </view>
          </picker>
        </view>
      </AtModalContent>
      <AtModalAction>
        <button @tap="addSleepTimeRecord" class="custom-button">提交</button>
      </AtModalAction>
    </AtModal>
<!--    醒来-->
    <AtModal :isOpened="isWakeUpCreateActionSheetOpen">
      <AtModalContent>
        <view>
          <picker
            mode='date'
            :value="wakeUpDate"
            @change="wakeUpDateChange"
          >
            <view class='input-row'>
              <view class='input-row__label'>醒来日期</view>
              <view class='input-row__content'>{{wakeUpDate}}</view>
            </view>
          </picker>
          <picker
            mode='time'
            :value="wakeUpTime"
            @change="wakeUpTimeChange"
          >
            <view class='input-row'>
              <view class='input-row__label'>醒来时间</view>
              <view class='input-row__content'>{{wakeUpTime}}</view>
            </view>
          </picker>
        </view>
      </AtModalContent>
      <AtModalAction>
        <button @tap="addWakeUpTimeRecord" class="custom-button">提交</button>
      </AtModalAction>
    </AtModal>
  </view>


</template>

<script lang="ts">
import "./index.less";
import Taro from "@tarojs/taro";
import helloTitle from "../../../common-components/hello-title/hello-title";
import CircleProgressBar from "../../../common-components/circle-progress/circle-progress.vue";
import placeholder from '../../../assets/images/placeholder-1.svg'
import LineChart from "../../../common-components/line-chart/line-chart.vue";
import {getHistoryData, updateSleep} from "../../../services/healthy-data-service";
import findIndex from 'lodash.findindex';
import get from 'lodash.get';
import {AtModal, AtModalHeader, AtModalContent, AtModalAction} from 'taro-ui-vue'
import dayjs from 'dayjs';
/**
 * consciousTime: 10
 depthTime: 10
 shallowTime: 0
 silentHeartRate: 0
 startTime: 1631537657659
 totalTime: 10
 wakeUpTime: 1631537657659
 */
interface SleepDataResult {
  dayOfMonth: Number,
  dayOfWeek: Number,
  value: {
    totalTime: Number,
    consciousTime: Number,
    depthTime: Number,
    shallowTime: Number,
    silentHeartRate: Number,
    startTime: Number,
    wakeUpTime: Number,
  }
}

export default {
  components: {
    LineChart,
    CircleProgressBar,
    helloTitle,
    AtModal, AtModalContent, AtModalAction
  },
  data() {
    return {
      latestSleepData: 8.5,
      placeholder,
      weekChartData: null,
      monthChartData: null,
      sleepChartDateType:1,
      isCreateActionSheetOpen:false,
      isWakeUpCreateActionSheetOpen:false,
      startSleepTime:"",
      startSleepDate:"2020-09-01",
      wakeUpTime:"",
      wakeUpDate:"2020-09-01",
    };
  },
  methods: {
    handleSleepTimeClose(){
      this.isCreateActionSheetOpen = false;
    },
    handleWakeUpTimeClose(){
      this.isWakeUpCreateActionSheetOpen = false;
    },
    async addSleepTimeRecord(){
      await updateSleep({startTime:dayjs(`${this.startSleepDate} ${this.startSleepTime}`).valueOf()})
      await this.initData();
    },
    async addWakeUpTimeRecord(){
      await updateSleep({wakeUpTime:dayjs(`${this.wakeUpDate} ${this.wakeUpTime}`).valueOf()})
      await this.initData();
    },
    sleepTimeChange(e){
      this.startSleepTime = e.detail.value;
      console.log(e)
    },
    wakeUpTimeChange(e){
      console.log(e)
      this.wakeUpTime = e.detail.value;
    },
    sleepDateChange(e){
      this.startSleepDate = e.detail.value;
      console.log(e)
    },
    wakeUpDateChange(e){
      console.log(e)
      this.wakeUpDate = e.detail.value;
    },
    showCreateActionSheet() {
      this.isCreateActionSheetOpen = true;
    },
    showWakeUpCreateActionSheetOpen() {
      debugger
      this.isWakeUpCreateActionSheetOpen = true;
    },
    async initData(){
      this.isCreateActionSheetOpen = false;
      const weekResult: SleepDataResult[] = await getHistoryData("DAY_OF_WEEK", "SLEEP");
      const monthResult: SleepDataResult[] = await getHistoryData("DAY_OF_MONTH", "SLEEP");
      console.log("睡眠数据",weekResult)
      this.weekChartData = this.formatChartData(weekResult,7);
      this.monthChartData = this.formatChartData(monthResult,30);
      this.latestSleepData = get(weekResult[weekResult.length-1],"value.totalTime","--");
      this.startSleepTime = dayjs(get(weekResult[weekResult.length-1],"value.startTime",0)).format("HH:MM");
      this.wakeUpTime = dayjs(get(weekResult[weekResult.length-1],"value.wakeUpTime",0)).format("HH:MM");
    },
    showWeekChart() {
      this.sleepChartDateType = 1;
    },
    showMonthChart() {
      this.sleepChartDateType = 2;
    },
    // 把数据格式化成 ${daysNumber} 天的数据
    formatChartData(data: SleepDataResult[], daysNumber: number) {
      const baseConfig = {
        yAxis: {
          unit: 1,
          base: 6,
          top: 7,
          display: [
            // 必须按顺序
            {value: 6, label: "6h"},
            {value: 7, label: "7h"},
            {value: 8, label: "8h"},
          ],
        },
        dataset: [],
      }
      for (let i = 1; i <= daysNumber; i++) {
        const index = findIndex(data, (item: SleepDataResult) => item.dayOfWeek === i);
        baseConfig.dataset.push({value: get(data[index], "value.totalTime", 0)});
      }
      return baseConfig;
    }
  },

  async created() {
    await this.initData();
  },
};
</script>
